package client;

import java.io.*;
import java.nio.ByteBuffer;
import java.security.*;
import javax.crypto.Cipher;

public class PairKey {

    private PublicKey pubKey;
    private PrivateKey priKey;

    public PairKey() {
        try {
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            keyGen.initialize(512);
            KeyPair pair = keyGen.generateKeyPair();
            priKey = pair.getPrivate();
            pubKey = pair.getPublic();
        } catch (NoSuchAlgorithmException na) {
            System.out.println("Problem with RSA");
        }
    }

    public PublicKey getpublicKey() {
        return pubKey;
    }

    public PrivateKey getprivateKey() {
        return priKey;
    }

    public static  byte[] encrypt(String data,Key key) {
        byte buffer[] = data.getBytes();
        byte[] signedData = null;
        try {
            Cipher aesCipher = Cipher.getInstance(key.getAlgorithm());
            aesCipher.init(Cipher.ENCRYPT_MODE, key);
            
            signedData = aesCipher.doFinal(buffer);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return signedData;
    }
    public static  byte[] encrypt(byte[] data,Key key) {
        byte[] signedData = null;
        try {
            Cipher aesCipher = Cipher.getInstance(key.getAlgorithm());
            aesCipher.init(Cipher.ENCRYPT_MODE, key);
            
            //byte bytes [] = new byte[54];
//            int k =0 ;
//            for (int i = 0; i < data.length; i++) {
//                bytes [k++] = data[i];
//                if (i%54 == 53)
//                {
//                    aesCipher.update(bytes, i-53, 54);
//                    k = 0;
//                }
//            }
            signedData = aesCipher.doFinal();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return signedData;
    }

    public static  byte[] decrypt(byte[] cipher , Key key) {
        byte[] data =null;
        try {
            Cipher aesCipher = Cipher.getInstance(key.getAlgorithm());
            aesCipher.init(Cipher.DECRYPT_MODE, key);
            data = aesCipher.doFinal(cipher);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return data;
    }
} 
             
    
